<?php

namespace Encore\Admin\Controllers;

use Encore\Admin\Actions\Custom\ImportActionPermissionAction;
use Encore\Admin\Actions\Custom\ImportRoutePermissionAction;
use Encore\Admin\Actions\Custom\PermissionCreateFromMenuAction;
use Encore\Admin\Actions\Custom\PermissionMenuBatchSetAction;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\Str;

class PermissionController extends AdminController
{
    private string $transFileName;

    public function __construct()
    {
        $this->transFileName = Str::singular(config('admin.database.permissions_table'));
        parent::__construct();
    }

    /**
     * {@inheritdoc}
     */
    protected function title()
    {
        return trans('admin.permissions');
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $permissionModel = config('admin.database.permissions_model');
        $menuOptions = config('admin.database.menu_model')::parentOptions();
        $grid = new Grid(new $permissionModel());
        $grid->model()->with('adminMenu');
        $grid->model()->orderBy('id', 'desc');
        $grid->column('id', __("admin/$this->transFileName.id"))->sortable();
        $grid->column('adminMenu.title', __("admin/$this->transFileName.admin_menu_id"))->display(function ($title) {
            if (isset($this->adminMenu['icon'])) {
                return sprintf('<i class="fa %s text-navy"></i> %s', $this->adminMenu['icon'], $this->adminMenu['title']);
            }
            return $title;
        });
        $grid->column('name', __("admin/$this->transFileName.name"));
        $grid->column('slug', __("admin/$this->transFileName.slug"));
        $grid->column('http_path', __("admin/$this->transFileName.http_path"))->display(function ($path) {
            $colors = [
                'GET'     => 'green',
                'HEAD'    => 'gray',
                'POST'    => 'blue',
                'PUT'     => 'yellow',
                'DELETE'  => 'red',
                'PATCH'   => 'aqua',
                'OPTIONS' => 'light-blue',
                'ANY'     => 'red',
            ];

            return collect(explode("\n", $path))->map(function ($path) use ($colors) {
                $method = $this->http_method ?: ['ANY'];
                if (Str::contains($path, ':')) {
                    list($method, $path) = explode(':', $path);
                    $method = explode(',', $method);
                }

                $method = collect($method)->map(function ($name) {
                    return strtoupper($name);
                })->map(function ($name) use ($colors) {

                    $color = $colors[$name] ?? 'gray';
                    return "<span class='label bg-$color'>{$name}</span>";
                })->implode('&nbsp;');

                if (!empty(config('admin.route.prefix'))) {
                    $path = '/' . trim(config('admin.route.prefix'), '/') . $path;
                }

                return "<div style='margin-bottom: 5px;'>$method<code>$path</code></div>";
            })->implode('');
        });

        $grid->column('created_at', trans('admin.created_at'))->kind()->sortable();
        $grid->column('updated_at', trans('admin.updated_at'))->sortable()->kind();

        $grid->actions(function () {
        })->filter(function (Grid\Filter $filter) use ($menuOptions) {
            $filter->disableIdFilter();
            $filter->column(6, function () use ($filter) {
                $filter->like('name', __("admin/$this->transFileName.name"));
                $filter->like('slug', __("admin/$this->transFileName.slug"));
            });
            $filter->column(6, function () use ($filter, $menuOptions) {
                $filter->equal('admin_menu_id', '权限组')->select($menuOptions);
                $filter->where(function ($query) {
                    if (1 == $this->input) {
                        $query->where('slug', 'like', '%.action');
                    }
                    if (2 == $this->input) {
                        $query->where('slug', 'not like', '%.action');
                    }
                }, '权限类型')->select([1 => '动作', 2 => '路由']);
            });

            $filter->scope('no_menu_id', '未分组')->whereDoesntHave('adminMenu');
        });

        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new ImportActionPermissionAction())
                ->append(new ImportRoutePermissionAction())
                ->append(new PermissionCreateFromMenuAction());
        });

        $grid->disableRowSelector(false)->batchActions(function (Grid\Tools\BatchActions $action) {
            $action->add(new PermissionMenuBatchSetAction());
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id): Show
    {
        $permissionModel = config('admin.database.permissions_model');

        $show = new Show($permissionModel::findOrFail($id));

        $show->field('id', __("admin/$this->transFileName.id"));
        $show->field('adminMenu.title', __("admin/$this->transFileName.admin_menu_id"));
        $show->field('slug', __("admin/$this->transFileName.slug"));
        $show->field('name', __("admin/$this->transFileName.name"));

        $show->field('http_path', trans('admin.route'))->unescape()->as(function ($path) {
            return collect(explode("\r\n", $path))->map(function ($path) {
                $method = $this->http_method ?: ['ANY'];

                if (Str::contains($path, ':')) {
                    list($method, $path) = explode(':', $path);
                    $method = explode(',', $method);
                }

                $method = collect($method)->map(function ($name) {
                    return strtoupper($name);
                })->map(function ($name) {
                    return "<span class='label label-primary'>{$name}</span>";
                })->implode('&nbsp;');

                if (!empty(config('admin.route.prefix'))) {
                    $path = '/' . trim(config('admin.route.prefix'), '/') . $path;
                }

                return "<div style='margin-bottom: 5px;'>$method<code>$path</code></div>";
            })->implode('');
        });

        $show->field('created_at', trans('admin.created_at'));
        $show->field('updated_at', trans('admin.updated_at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form(): Form
    {
        $permissionModel = config('admin.database.permissions_model');
        $table = config('admin.database.permissions_table');

        $form = new Form(new $permissionModel());

        $form->text('slug', __("admin/$this->transFileName.slug"))
            ->icon('fa-tag')
            ->creationRules("required|max:64|unique:$table,slug")
            ->updateRules("required|max:64|unique:$table,slug,{{id}}");

        $form->text('name', __("admin/$this->transFileName.name"))
            ->creationRules("required|max:32|unique:$table,name")
            ->updateRules("required|max:32|unique:$table,name,{{id}}");

        $form->select('admin_menu_id', __("admin/$this->transFileName.admin_menu_id"))
            ->options(config('admin.database.menu_model')::parentOptions())
            ->rules('required');

        $form->multipleSelect('http_method', __("admin/$this->transFileName.http_method"))
            ->options($this->getHttpMethodsOptions())
            ->help(trans('admin.all_methods_if_empty'));

        $form->textarea('http_path', __("admin/$this->transFileName.http_path"));

        return $form;
    }

    /**
     * Get options of HTTP methods select field.
     *
     * @return array
     */
    protected function getHttpMethodsOptions()
    {
        $model = config('admin.database.permissions_model');

        return array_combine($model::$httpMethods, $model::$httpMethods);
    }
}
